package com.mvc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.common.core.BaseController;
import com.common.utils.DateUtil;
import com.common.utils.IPKit;
import com.common.utils.JsonUtil;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.upload.UploadFile;
import com.mvc.model.CDKey;
import com.mvc.request.FinalData;
import com.mvc.request.ReqCDKeyAdd;
import com.mvc.request.ReqCDKeyDelete;
import com.mvc.request.ReqCDKeyPage;
import com.mvc.request.ReturnData;
import com.mvc.response.CDKeyUI;
import com.mvc.response.PageList;
import com.mvc.response.RspPage;
import com.mvc.service.CDKeyService;
import com.mvc.service.impl.CDkeyServiceImpl;

public class CDKeyController extends BaseController {

	CDKeyService cdKeyService = new CDkeyServiceImpl();

	// WebUI
	public void addView() {
		render("add.jsp");

	}

	// WebUI
	public void search() {
		render("search.jsp");
	}

	// WebUI 业务
	public void searchCodeKey() throws Exception {

		ReqCDKeyPage req = new ReqCDKeyPage();
		FinalData finalData = new FinalData();
		req.setFinalData(finalData);

		req.setName(getPara("name"));
		req.setType(getParaToInt("type", 2));
		req.setNowPage(getParaToInt("pageIndex", 0) + 1);
		req.setPageSize(10);

		ReturnData<RspPage<CDKey>> data = cdKeyService.queryPage(req);

		PageList<CDKeyUI> pageList = new PageList<CDKeyUI>();
		if (data.getCode() == 200) {
			List<CDKey> list = data.getData().getList();
			List<CDKeyUI> uiList = new ArrayList<CDKeyUI>(list.size());
			for (CDKey key : list) {
				
				CDKeyUI ui = new CDKeyUI();
				ui.setId(key.getInt(CDKey.TableField.ID.value));
				ui.setCode(key.getStr(CDKey.TableField.CODEKEY.value));
				ui.setContent(key.getStr(CDKey.TableField.CONTENT.value));
				ui.setName(key.getStr(CDKey.TableField.NAME.value));

			
				long viableSize = key.getLong(CDKey.TableField.VIABLESIZE.value);
				long userSize = key.getLong(CDKey.TableField.USERSIZE.value);
				
				
				if (viableSize <= 0) {
					ui.setViableSize("<span class=\"badge badge-error\">0</span>");
					
				} else {
					ui.setViableSize("<span class=\"badge badge-success\">"+viableSize+"</span>");
				}
				
				ui.setUserSize("<span class=\"badge badge-success\">"+userSize+"</span>");
			

				Date createTime = key
						.getDate(CDKey.TableField.CREATETIME.value);
				ui.setCreateTime(DateUtil.friendTime(createTime));

				Date readTime = key.getDate(CDKey.TableField.READTIME.value);
				if (readTime != null) {
					String time = "<font color=\"#FF4081\">"
							+ DateUtil.friendTime(readTime) + "</font>";
					ui.setReadTime(time);
				} else {
					ui.setReadTime("");
				}
				uiList.add(ui);
			}
			pageList.setResults(data.getData().getTotalPage()
					* req.getPageSize());
			pageList.setRows(uiList);
			pageList.setError("");
			pageList.setHasError(false);
		}

		renderJson(JsonUtil.toJson(pageList));

	}

	// WebUI 添加业务
	public void add() throws Exception {

		ReqCDKeyAdd add = new ReqCDKeyAdd();
		if (add.getFinalData() == null) {
			FinalData finalData = new FinalData();
			String ip = IPKit.getRealIp(getRequest());
			finalData.setMac(ip);
			finalData.setCode(100);
			finalData.setType("web");
			add.setFinalData(finalData);
		}

		add.setCodeKey(getPara("codeKey"));
		add.setName(getPara("name"));
		add.setContent(getPara("content"));
		add.setViableSize(getParaToLong("size"));
		ReturnData<Boolean> data = cdKeyService.add(add);
		renderJson(JsonUtil.toJson(data));
	}

	public void delete() {
		ReqCDKeyDelete req = new ReqCDKeyDelete();
		req.setId(getParaToInt("id"));
		ReturnData<Boolean> data = cdKeyService.delete(req);
		renderJson(JsonKit.toJson(data));
	}

	public void importExcel() {
		// 获取文件
		UploadFile file = getFile("Filedata");

		if (file == null) {
			renderJson(JsonUtil.toJson(new ReturnData<Boolean>(false, 200, "")));
			return;
		}

		boolean isSuccess = true;
		try {
			// 处理导入数据
			String path = file.getFile().getAbsolutePath();
			List<Map<Integer, String>> list = dealDataByPath(path); // 分析EXCEL数据
			List<CDKey> insterList = new ArrayList<>(list.size());
			Date date = new Date();
			for (Map<Integer, String> map : list) { // 遍历取出的数据，并保存

				CDKey m = new CDKey();
				m.set(CDKey.TableField.NAME.value, map.get(0));
				m.set(CDKey.TableField.CODEKEY.value, map.get(1));
				m.set(CDKey.TableField.VIABLESIZE.value, map.get(2));
				m.set(CDKey.TableField.CONTENT.value, map.get(3));
				m.set(CDKey.TableField.CREATETIME.value, date);
				insterList.add(m);
			}

			batchSave(insterList);

		} catch (Exception e) {
			System.out.println(e);
			isSuccess =false;

		} finally {
			file.getFile().delete();
		}
		renderJson(JsonUtil.toJson(new ReturnData<Boolean>(isSuccess,
				isSuccess ? 200 : 202, "")));
	}

	/**
	 * 分析excel的内容
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	private List<Map<Integer, String>> dealDataByPath(String path)
			throws FileNotFoundException, IOException {
		List<Map<Integer, String>> list = new ArrayList<Map<Integer, String>>();
		// 工作簿
		HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(new File(path)));

		HSSFSheet sheet = hwb.getSheetAt(0); // 获取到第一个sheet中数据

		for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {// 第二行开始取值，第一行为标题行

			HSSFRow row = sheet.getRow(i); // 获取到第i列的行数据(表格行)

			Map<Integer, String> map = new HashMap<Integer, String>();

			for (int j = 0; j < row.getLastCellNum(); j++) {

				HSSFCell cell = row.getCell(j); // 获取到第j行的数据(单元格)

				cell.setCellType(HSSFCell.CELL_TYPE_STRING);

				map.put(j, cell.getStringCellValue());
			}

			list.add(map);
		}

		return list;
	}

	/**
	 * 批量保存
	 * 
	 * @param modelList
	 */
	public void batchSave(List<CDKey> modelList) {
		// 判断list的大小,如果大于200条,则size/200分批次保存
		int size = modelList.size();
		if (200 >= size) {
			Db.batchSave(modelList, size);
			return;
		}
		int serial = size / 200;
		for (int i = 0; i < serial; i++) {
			Db.batchSave(modelList.subList(i * 200, i * 200 + 200), 200);
		}
		int remain = size - serial * 200;
		Db.batchSave(modelList.subList(serial * 200, size), remain);
	}
}
